<template>
  <div>
    <my-title title="账号注册"></my-title>
    <!-- 表单 -->
    <van-form submit-on-enter @submit="onSubmit">
      <van-field
        v-model="form.username"
        name="用户名"
        placeholder="请输入账号"
        :rules="[
        { required: true, message: '请填写用户名' },
        {pattern:/^[a-zA-Z0-9_-]{4,16}$/,message: '用户名格式错误'}
        ]"
      />
      <van-field
        v-model="form.password"
        type="password"
        name="密码"
        placeholder="请输入密码"
        :rules="[{ required: true, message: '请填写密码' },
        {pattern:/^(\w){5,12}$/,message: '密码格式错误'}]"
      />
      <van-field
        v-model="password2"
        type="password"
        name="二次密码"
        placeholder="请再次输入密码"
        :rules="[{ required: true, message: '请填写密码' },
        {pattern:/^(\w){5,12}$/,message: '密码格式错误'},
        { validator, message: '两次输入的密码不一致' }]"
      />
      <div style="margin: 16px;">
        <van-button block type="info" native-type="submit">注 册</van-button>
      </div>
    </van-form>
    <div class="log"><router-link to="/login">已有账号，去登录~</router-link></div>
  </div>
</template>

<script>
import { register } from '@/api/login.js'
import { Toast } from 'vant'
import MyTitle from '@/components/MyTitle'
export default {
  name: 'Register',
  data () {
    return {
      form: {
        username: '',
        password: ''
      },
      password2: ''
    }
  },
  components: {
    MyTitle
  },
  created () {

  },

  methods: {
    // 二次密码判断
    validator (val) {
      // console.log(val)
      return (val === this.form.password)
    },
    onClickLeft () {
      this.$router.back()
    },
    async onSubmit () {
      try {
        const res = await register(this.form)
        // console.log(res)
        if (res.data.status === 200) {
          this.$router.push('/login')
          Toast({
            message: res.data.description,
            icon: 'passed'
          })
        } else {
          Toast({
            message: res.data.description,
            icon: 'close'
          })
        }
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style scoped lang='less'>
/deep/.van-field__control{
    height: 60px;
    font-size: 18px;
  }
/deep/.van-button--info{
  background: rgb(28, 182, 118);
  font-size: 18px;
  height: 50px;
}
.log{
  // display: flex;

  a{
    width: 100%;
    text-align: center;
    display: block;
    color: #666;
    font-size: 14px;
  }
}
</style>
